import {
  ds
} from "../../../tools/data"
import {
  users
} from "../../../tools/users"
import {
  pages
} from '../../../tools/pages'
import {
  ui
} from '../../../tools/ui'
import {
  checkTool
} from "../../../tools/check";
import {
  dsFiles
} from "../../../tools/dsFiles";
import {
  coupon
} from '~/tools/coupon'

Page({
  data: {
    action: 'new',
    id: '',
    item: {
      visible: true,
      deliveryFee: 3.5
    },
    errMsg: "",
    specList: [],
    ticket: {}
  },
  async init() {
    const that = this
    if (this.data.action == 'edit') {
      const swiper = ds.coll('goods')
      swiper.where({
        _id: ds.cmd.eq(that.data.id)
      }).get({
        success: function (res) {
          if (res.data && res.data.length > 0) {
            const item = res.data[0]
            item.types = dsFiles.descFileTypeList(item.desc)
            that.setData({
              item: {
                ...that.data.item,
                ...item
              },
              specList: item.specList || [],
              ticket: item.ticket || {}
            })
            // console.log(item)
          }
        }
      });
    }
  },
  addSpec() {
    const specList = this.data.specList
    specList.push({});
    this.setData({
      specList
    });
  },
  addCoupon() {
    const {
      id,
      item
    } = this.data
    if (!id) return ui.toast(false, '请先保存商品信息')

    const paramItem = {
      goodsId: id,
      goodsTitle: item.title,
      userName: ' ',
      userId: 'prepend'
    }
    wx.navigateTo({
      url: `/pages/usercenter/coupon/edit/couponEdit?action=new&result=json&item=${JSON.stringify(paramItem)}`,
    })
  },
  couponCreated(coupon) {
    console.log('created', coupon)
    const couponList = (this.data.item.couponList ?? [])
    const index = couponList.findIndex(ele => ele._id == coupon._id)

    if (index >= 0) couponList[index] = coupon
    else couponList.push(coupon)
    this.setData({
      'item.couponList': couponList
    })
  },
  couponTap(e) {
    const coupon = ui.eventData(e, 'coupon')
    wx.navigateTo({
      url: `/pages/usercenter/coupon/edit/couponEdit?item=${JSON.stringify(coupon)}&result=json`,
    })
  },
  onDeleteCouponTap(e) {
    const id = ui.eventData(e, 'id')
    this.setData({
      'item.couponList': this.data.item.couponList.filter(ele => ele._id != id)
    })
    // coupon.deleteCoupon(id, res => {

    // })
  },
  delSpec(e) {
    const specList = this.data.specList
    specList.splice(e.target.dataset.index, 1)
    this.setData({
      specList
    })
  },
  selImg(tag) {
    wx.navigateTo({
      url: `../imgSelect/index?tag=${tag}`
    })
  },
  addImgClick() {
    this.setData({
      imgClickIndex: -1
    })
    this.selImg()
  },
  imgClick(e) {
    this.setData({
      imgClickIndex: e.target.dataset.index
    })
    this.selImg()
  },
  imgSelected(files, tag) {
    if (files.length <= 0) return
    const fileId = files[0]

    if (!dsFiles.isSupported(fileId)) return ui.delayToast(500, false, '不支持的媒体格式')

    const {
      item
    } = this.data

    const that = this
    const imgIndex = this.data.imgClickIndex

    if (tag == 'desc') { // 描述
      if (!item.desc) item.desc = []
      const desc = item.desc
      if (imgIndex >= 0) desc[imgIndex] = fileId
      else desc.push(fileId)
      item.types = dsFiles.descFileTypeList(desc)
      this.setData({
        item
      })
    } else { // 主图
      if (dsFiles.isVideo(fileId)) return ui.delayToast(500, false, '主图不支持视频')
      const images = item.images || []
      if (imgIndex >= 0) images[imgIndex] = fileId
      else images.push(fileId)
      item.images = images
      that.setData({
        item
      })
    }
  },
  save() {
    if (!checkTool.check(this.getFields())) return
    const {
      ticket
    } = this.data

    const item = this.data.item
    if (item.deduct) {
      let num = parseFloat(item.deduct)
      if ((item.deduct + '').endsWith('%')) num /= 100
      item.deduct = num
    }

    item.specList = this.data.specList
    item.thumb = item.images[0] || ''
    item.ticket = ticket
    item.updateTime = new Date().getTime()
    item.minNum = parseInt(item.minNum ?? "1")
    item.deliveryFee = Number(item.deliveryFee ?? 3.5)
    console.log(item)
    ui.loading()
    ds.cloudUpdate('goods', this.data.id, item, res => {
      ui.loading(false)
      const success = res.errMsg.endsWith(':ok')
      ui.toast(success, '', () => {
        pages.back(prevPage => {
          prevPage.init()
        });
      })
    })
  },
  getFields() {
    const {
      item,
      desc,
      specList
    } = this.data
    const fields = [{
      value: item.title,
      title: '标题'
    }, {
      value: (item.tags || []).join(""),
      title: '标签',
    }, {
      value: item.deduct,
      regex: "0(\\.\\d+)?|(\\d+%)|(\\d+)",
      title: '提成'
    }, {
      value: item.num,
      allowEmpty: true,
      regex: "\\d+",
      title: '存货量'
    }, {
      value: item.minNum,
      allowEmpty: true,
      regex: "\\d+",
      title: '起订量'
    }, {
      value: item.deliveryFee,
      allowEmpty: false,
      regex: checkTool.CommonRegex.decimal,
      title: '配送提成'
    }, {
      value: item.images,
      fn: images => images?.length > 0,
      title: '图片'
    }, {
      value: desc,
      fn: desc => item.desc?.length > 0,
      title: '商品描述'
    }, {
      value: specList,
      fn: list => list.length > 0,
      title: '分类'
    }, {
      value: item.deadline,
      fn: val => (!item.promotion) || val,
      title: '自动下架时间'
    }, {
      value: item.num,
      fn: num => (!item.promotion) || num,
      title: '存货量'
    }]

    specList.forEach(ele => {
      fields.push({
        value: ele.specName,
        title: '分类名'
      })
      fields.push({
        value: ele.price,
        regex: checkTool.CommonRegex.decimal,
        title: '现价'
      })
      fields.push({
        value: ele.vipPrice,
        regex: checkTool.CommonRegex.decimal,
        title: '会员价'
      })
      fields.push({
        value: ele.originPrice,
        regex: checkTool.CommonRegex.decimal,
        title: '原价'
      })
    })

    return fields
  },
  onAddDesc(e) {
    const imgClickIndex = -1
    this.setData({
      imgClickIndex
    })
    this.selImg('desc')
  },
  onDelDesc(e) {
    const index = e.target.dataset.index
    const item = this.data.item,
      desc = item.desc
    desc.splice(index, 1)
    item.types = dsFiles.descFileTypeList(desc)
    this.setData({
      item
    })
  },
  onClickDesc(e) {
    const imgClickIndex = e.target.dataset.index
    this.setData({
      imgClickIndex
    })
    this.selImg('desc')
  },
  onDel() {
    // if (this.data.item.couponList?.length > 0)
    //   return ui.toast(false, '请先删除优惠券')

    ui.confirm('确定删除吗？', res => {
      if (!res) return
      ui.loading()
      ds.coll('goods').where({
          _id: this.data.id
        }).remove()
        .then(res => {
          // console.log('del')
          pages.back(prePage => {
            prePage.init()
          })
        })
    })

  },
  onTicketBtnTap() {
    wx.navigateTo({
      url: '../ticketEdit/ticketEdit?ticket=' + JSON.stringify(this.data.ticket),
    })
  },
  ticketCallback(values) {
    this.setData({
      ticket: values
    })
    // console.log(this.data.ticket)
  },
  onValueChange(e) {
    const name = e.currentTarget.dataset.name
    let value = e.detail.value
    const item = this.data.item
    if (name == 'tags') {
      value = value.replaceAll(' ', '').split(/[,，]/);
    } else if (name == 'top') {
      value = (value ? 1 : 0)
      if (value) this.singleSwitch('visible')
    } else if (name == 'deadline') {
      value = e.detail.timestamp
      item.top = false
    }

    if (name != 'visible' && value) item.top = false
    this.singleSwitch(name)
    // console.log(name, value)
    this.data.item[name] = value
    this.setData({
      item
    })
  },
  singleSwitch(name) {
    const {
      item
    } = this.data
    const values = ['visible', 'promotion', 'fastDelivery']
    if (values.indexOf(name) < 0) return

    values.forEach(ele => item[ele] = (ele == name))
    this.setData({
      item
    })
  },
  deliveryFeeUnitChange(e) {
    const name = e.target.dataset.name
    const item = this.data.item
    item.deliveryFee[name] = e.detail.value
    this.setData({
      item
    })
  },
  onSpecChange(e) {
    const specList = this.data.specList
    const name = e.target.dataset.name,
      index = e.target.dataset.index
    specList[index][name] = e.detail.value
    this.setData({
      specList
    })
  },
  onDelImg(e) {
    const index = e.target.dataset.index
    const item = this.data.item
    const images = item.images || []
    item.images = images.filter((ele, i) => i != index)
    this.setData({
      item
    })
  },
  onLoad(option) {
    if (option.action) {
      this.setData({
        action: option.action,
        id: option.id
      })
    }
    // console.log(this.data.action)
    this.init();
  },
});